package com.rattkin.controller.extension
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	
	import mx.collections.ArrayCollection;

	public class EventSequenceDispatcher
	{		
		[Bindable] static public var EVENT_FINISHED:String = "eventSequenceDispatcher_eventFinished";
		
		private var eventMapDispatcher:IEventDispatcher;		
		private var events:ArrayCollection;	
		
		public function EventSequenceDispatcher(eventMapDispatcher:IEventDispatcher) {
			this.events = new ArrayCollection();
			this.eventMapDispatcher = eventMapDispatcher;
		}		
		
		public function addEvent(event:Event):void {
			events.addItem(event);		
		}
		
		public function beginDispatching():void {
			eventMapDispatcher.addEventListener(EventSequenceDispatcher.EVENT_FINISHED, eventFinished);
			dispatchNext();
		}
				
		private function dispatchNext():void {			
			var event:Event = events.removeItemAt(0) as Event;
			eventMapDispatcher.dispatchEvent(event);	
		}
		
		public function eventFinished(event:Event):void {
			if (events != null && events.length > 0) {	
				dispatchNext();
			}
			else {
				dispatchingFinished();				
			}
		}		
		
		private function dispatchingFinished():void {
			eventMapDispatcher.removeEventListener(EventSequenceDispatcher.EVENT_FINISHED, eventFinished);
		}		
		
				
	}
}